package pattern.singleton;

import java.io.ObjectStreamException;
import java.io.Serializable;

/**
 * <b>【静态内部类】【推荐】</b><br>
 * Lazy Loading: 是 <br>
 * 线程安全: 是 <br>
 *
 * @Author: wangxiaonan
 * @Date: 2019/3/12
 **/
public class Singleton7 implements Serializable {

    private static final long serialVersionUID = 1L;

    private Singleton7() {
        // 防止暴力反射攻击
        if (SingletonHolder.INSTANCE != null) {
            throw new IllegalStateException("You cannot do it in this way!");
        }
    }

    public static Singleton7 getInstance() {
        return SingletonHolder.INSTANCE;
    }

    /**
     * 如果要序列化对象，必须重写这个方法，以保证反序列化之后对象和序列化之前一致
     */
    private Object readResolve() throws ObjectStreamException {
        return SingletonHolder.INSTANCE;
    }

    private static class SingletonHolder {

        private static final Singleton7 INSTANCE = new Singleton7();

    }
}
